import network
import utime as time
from modem import net
import mod_system

# Global variables
g_connect_status = False
# 网络连接失败次数
g_connect_error_times = 0
Net = None


def init():
    """Initialize network module"""
    print("[NETWORK] Network module initialized")
    connect_network()
    return True


def on_4g_cb(args):
    global g_connect_status
    pdp = args[0]
    netwk_sta = args[1]
    if netwk_sta == 1:
        g_connect_status = True
        print("[NETWORK] 4G connected")
    else:
        g_connect_status = False
        print("[NETWORK] 4G disconnected")


def getNetFlag():
    """Get network connection status"""
    global g_connect_status
    return g_connect_status


def connect_network(timeout_ms=10000):
    """Connect to network with timeout"""
    global Net, g_connect_status, g_connect_error_times

    Net = network.NetWorkClient()
    g_register_network = False

    if Net._stagecode is not None and Net._stagecode == 3 and Net._subcode == 1:
        g_register_network = True
    else:
        print(
            "[NETWORK] Network register failed, code: {}, {}".format(
                Net._stagecode, Net._subcode
            )
        )
        g_register_network = False

    if g_register_network:
        Net.on(1, on_4g_cb)
        Net.connect(None)
    else:
        g_connect_error_times += 1
        print("[NETWORK] ===> Network register failed {} times".format(g_connect_error_times))
        if g_connect_error_times > 5:
            mod_system.restart()
        return False

    # 等待连接成功（加入超时机制）
    start_time = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start_time) < timeout_ms:
        if g_connect_status:
            print("[NETWORK] Network register successed")
            return True
        time.sleep_ms(100)

    print("[NETWORK] Network connect timeout")
    g_connect_error_times += 1
    if g_connect_error_times > 5:
        mod_system.restart()
    return False


def start():
    """Start network module"""
    print("[NETWORK] Network module started")
    return True


def stop():
    """Stop network module"""
    global g_connect_status, Net
    try:
        if Net and g_connect_status:
            Net.disconnect()
            g_connect_status = False
            print("[NETWORK] Network disconnected")

        print("[NETWORK] Network module stopped")

    except Exception as e:
        print("[NETWORK] Stop network error: {}".format(e))


def get_network_status():
    """Get network status"""
    try:
        signal_strength = net.getCsq()
        return {
            "connected": g_connect_status,
            "signal_strength": signal_strength,
        }
    except Exception as e:
        print("[NETWORK] Get network status error: {}".format(e))
        return {"connected": False, "signal_strength": 0}


def get_module_info():
    """Get module info"""
    return {
        "name": "Network Module",
        "version": "v1.0.0",
        "description": "Simple network connection",
    }


def cleanup():
    """Cleanup network module"""
    try:
        stop()
        print("[NETWORK] Network cleanup completed")
    except Exception as e:
        print("[NETWORK] Network cleanup error: {}".format(e))


def is_connected():
    """Check if network is connected"""
    return g_connect_status
